package com.example.tliaswebmanagement.service.impl;

import com.example.tliaswebmanagement.mapper.ClazzMapper;
import com.example.tliaswebmanagement.pojo.Clazz;
import com.example.tliaswebmanagement.pojo.ClazzQueryParam;
import com.example.tliaswebmanagement.pojo.Emp;
import com.example.tliaswebmanagement.pojo.PageResult;
import com.example.tliaswebmanagement.service.ClazzService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {
    private final ClazzMapper clazzMapper;

    public ClazzServiceImpl(ClazzMapper clazzMapper) {
        this.clazzMapper = clazzMapper;
    }

    /**
     * 班级列表查询
     */
    @Override
    public PageResult<Clazz> paginationClazz(ClazzQueryParam clazzQueryParam) {
        PageHelper.startPage(clazzQueryParam.getPage(), clazzQueryParam.getPageSize());
        List<Clazz> clazzList = clazzMapper.list(clazzQueryParam);
        Page<Clazz> p = (Page<Clazz>) clazzList;
        // 获取当前时间
        LocalDate now = LocalDate.now();
        // 循环遍历每个班级，调用方法设置状态
        for (Clazz clazz : clazzList) {
            setClazzStatus(clazz, now);
        }

        return new PageResult<Clazz>((int) p.getTotal(), p.getResult());
    }
    // 判断班级状态
    private void setClazzStatus(Clazz clazz, LocalDate now) {
        LocalDate begin = clazz.getBeginDate();
        LocalDate end = clazz.getEndDate();

        if (end != null && now.isAfter(end)) {
            clazz.setStatus("已结课");
        } else if (begin != null && now.isBefore(begin)) {
            clazz.setStatus("未开班");
        } else {
            clazz.setStatus("在读中");
        }
    }

    /**
     * 新增班级
     */
    @Override
    public void addClazz(Clazz clazz) {
        // 设置时间
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.addClazz(clazz);
    }

    /**
     * 根据 ID 查询，数据回显
     */
    @Override
    public Clazz getClazzInfo(Integer id) {
        return clazzMapper.getId(id);
    }

    /**
     * 修改班级信息
     */
    @Override
    public void updateClazzById(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.updateClazzById(clazz);
    }

    /**
     * 删除班级
     */
    @Override
    public void deleteById(Integer id) {
        clazzMapper.deleteById(id);
    }

    /**
     * 查询所有班级
     */
    @Override
    public List<Clazz> findAllClazz() {
        return clazzMapper.findAllClazz();
    }
}
